//
//  UtilTools.m
//  xiaoyixiu
//
//  Created by 赵岩 on 16/6/14.
//  Copyright © 2016年 柯南. All rights reserved.
//

#import "UtilTools.h"
#import <CoreTelephony/CTCellularData.h>
#import <CoreFoundation/CoreFoundation.h>
//#import "lame.h"

@implementation UtilTools
static SystemSoundID shake_sound_enter_id = 0;

#pragma mark   判空方法

+ (BOOL)isBlankString:(id)string
{
    string = [NSString stringWithFormat:@"%@",string];
    
    if (string == nil) {
        return YES;
    }
    
    if (string == NULL) {
        return YES;
    }
    if ([string isEqual:[NSNull null]]) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    if([string isEqualToString:@"<null>"])
    {
        return YES;
    }
    if ([string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length==0) {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isBlankArray:(NSArray *)array
{
    if (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
    {
        return YES;
    }
    return NO;
}

+(BOOL)isBlankDictionary:(NSDictionary *)dictionary;
{
    if (dictionary == nil || [dictionary isKindOfClass:[NSNull class]] || dictionary.count == 0)
    {
        return YES;
    }
    return NO;
}

//身份证号
+ (BOOL)validateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

//邮箱
+ (BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//密码
+(BOOL)password:(NSString *)password
{
    NSString * regex = @"^[A-Za-z0-9]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}




+ (BOOL)isLogin:(NSString *)oneTime andTwoTime:(NSString *)twoTime {
    
    //时间戳转换成日期
    NSDate *oneDate = [NSDate dateWithTimeIntervalSince1970:[oneTime intValue]];
    NSDate *twoDate = [NSDate dateWithTimeIntervalSince1970:[twoTime intValue]];
    //系统自带计算时间，返回的是秒
    NSTimeInterval time = [twoDate timeIntervalSinceDate:oneDate];
    double valiableTime = time;
    //计算天数
    NSInteger val_days = valiableTime/60/60/24;
    
    if (labs(val_days)>=1) {
        return YES;
    }
    
    return NO;
}



#pragma  mark   转换方法
//url转义
+(NSString *)URLEncodedString:(NSString *)string
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = string;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}


//格式化时间字符串
+(NSString *)getNowTimeWithString:(NSString *)aTimeString{
    
    
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 截止时间date格式
    NSDate  *expireDate = [formater dateFromString:aTimeString];
    NSDate *data = [expireDate dateByAddingTimeInterval:24.0*60*60];
    
    NSDate  *nowDate = [NSDate date];
    // 当前时间字符串格式
    NSString *nowDateStr = [formater stringFromDate:nowDate];
    // 当前时间date格式
    nowDate = [formater dateFromString:nowDateStr];
    
    NSTimeInterval timeInterval =[data timeIntervalSinceDate:nowDate];
    
    int days = (int)(timeInterval/(3600*24));
    int hours = (int)((timeInterval-days*24*3600)/3600);
    int minutes = (int)(timeInterval-days*24*3600-hours*3600)/60;
    
    NSString *hoursStr;NSString *minutesStr;
    
    //小时
    hoursStr = [NSString stringWithFormat:@"%d",hours];
    //分钟
    if(minutes<60)
        return @"刚刚";
    else
        minutesStr = [NSString stringWithFormat:@"%d",minutes];
    //秒
    
    
    if (hours<=0&&minutes<=0) {
        return @"超过24小时";
    }
    if (days) {
        return [NSString stringWithFormat:@"剩%@小时 %@分",hoursStr, minutesStr];
    }
    return [NSString stringWithFormat:@"剩%@小时 %@分",hoursStr , minutesStr];
}

+ (NSString *)dateConvertToString:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}
+(NSData *)getCompressionImage:(UIImage *)image toSize:(int)size{
    NSData *   _headImageData;
    //    if (UIImagePNGRepresentation(image) == nil){
    _headImageData = UIImageJPEGRepresentation(image, 1);
    double scaleNum = (double)size*1024 / _headImageData.length;
    
    if (scaleNum < 1) {
        _headImageData = UIImageJPEGRepresentation(image, scaleNum);
    }
    //                } else {
    //                    _headImageData = UIImagePNGRepresentation(image);
    //                }
    
    
    return _headImageData;
}
+(NSData *)NSdataConvertToImage:(UIImage *)image compress:(CGFloat)compressionQuality
{
    NSData *data;
    if (UIImagePNGRepresentation(image)) {
        data=UIImagePNGRepresentation(image);
    }
    else
    {
        data=UIImageJPEGRepresentation(image, compressionQuality);
    }
    return data;
}
+ (UIImage *)cutImage:(UIImage*)image andSize:(CGSize)size
{
    //压缩图片
    CGSize newSize;
    CGImageRef imageRef = nil;
    
    if ((image.size.width / image.size.height) < (size.width / size.height)) {
        newSize.width = image.size.width;
        newSize.height = image.size.width * size.height / size.width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
    } else {
        newSize.height = image.size.height;
        newSize.width = image.size.height * size.width / size.height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
    }
    
    UIImage* smallImage = [UIImage imageWithCGImage:imageRef];   //注意蓝色的部分
    CGImageRelease(imageRef);
    
    return smallImage;
}

+ (NSString *)jsonString:(NSDictionary *)dic;
{
    NSError *error =nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


+ (NSString *)arrayConvertToString:(NSArray *)array
{
    //把数组转换为字符串
    NSError *error;
    NSData *textData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *textString = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
    return textString;
}
+ (NSArray *)stringConvertToArray:(NSString *)string
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return array;
}

//时间戳转换成当前时区的日期
+ (NSString *)getDateFromDateLine:(NSString *)dateLine format:(NSString *)format
{
    //上传时的时间戳（格林尼治时间戳）
    NSString *timeIntervalSince1970 = dateLine;
    //把时间戳转换成日期（格林尼治日期）
    NSTimeInterval dateInt=[timeIntervalSince1970 doubleValue];
    if (timeIntervalSince1970.length==13) {
        dateInt=dateInt/1000;
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInt];
    //初始化时间格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //给时间格式设置格式参数
    //YYYY:MM:dd-HH:mm:ss
    [dateFormatter setDateFormat:format];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//东八区时间
    
    //获取date对应dateFormatter格式的字符串（中国 东八区日期）
    NSString *timeString = [dateFormatter stringFromDate:date];
    return timeString;
}
/**
 *  获取相差的天数
 *
 *  @return 获取相差的天数
 */
+ (int)getDifferenceNumberDays:(NSString *)format dataString:(NSString*)dataString
{
    
    //给时间格式设置时区（中国 东八区）
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setTimeZone:timeZone];
    
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [inputFormatter setDateFormat:format];
    NSDate* inputDate = [inputFormatter dateFromString:dataString];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    NSInteger interval = [zone secondsFromGMTForDate: inputDate];
    
    NSDate *localeDate = [inputDate dateByAddingTimeInterval: interval];
    
    
    //取两个日期对象的时间间隔：
    //这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:typedef double NSTimeInterval;
    NSTimeInterval time=[[NSDate date] timeIntervalSinceDate:localeDate];
    
    int days=((int)time)/(3600*24);
    //int hours=((int)time)%(3600*24)/3600;
    //NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];
    return days;
}
/**
 *  获取当前时区的时间
 *
 *  @return 当前时区的时间
 */
+(NSString *)getNowTimeTimestamp2{
    
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval a=[dat timeIntervalSince1970];
    
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    
    
    
    return timeString;
    
}
+(NSDateComponents *)getDiffetenceAllowDays:(NSString *)lastTime NetTime:(NSString *)newTime{
    // 2.将时间转换为date
    //  时区相差8个小时 加上这个时区即是北京时间
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger delta = [timeZone secondsFromGMT];
    // 两个时间戳转换日期类//
//    [takeCarTime doubleValue]  //  << 这里除以1000 我们后台传来的时间戳有问题
    NSDate *DRstartDate = [[NSDate alloc] initWithTimeIntervalSince1970:[lastTime doubleValue] + delta];
    NSDate *DRendDate = [[NSDate alloc] initWithTimeIntervalSince1970:[newTime doubleValue]/1000 + delta];// 日历对象 （方便比较两个日期之间的差距）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // NSCalendarUnit 枚举代表想获得哪些差值 NSCalendarUnitYear 年 NSCalendarUnitWeekOfMonth 月
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit fromDate:DRendDate toDate:DRstartDate options:0];
    // 获得某个时间的年月日时分秒
    //        NSDateComponents *createDateCmps = [calendar components:unit fromDate:DRstartDate];
    //        NSDateComponents *nowCmps = [calendar components:unit fromDate:DRendDate];
    NSLog(@"剩余%ld天,%ld小时%ld分", cmps.day ,cmps.hour, cmps.minute);
    NSLog(@"相差%ld小时",cmps.hour);
    
    
    
  
    
    return cmps;
}
+(NSString *)getLastTime:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:time];//model.created_at 时间
    //八小时时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:timeDate];
    NSDate *mydate = [timeDate dateByAddingTimeInterval:interval];
    NSDate *nowDate = [[NSDate date]dateByAddingTimeInterval:interval];
    //两个时间间隔
    NSTimeInterval timeInterval = [mydate timeIntervalSinceDate:nowDate];
    timeInterval = -timeInterval;
    long temp = 0;
    //    NSString *time;
    if (timeInterval<60) {
        
        NSString * str = [NSString stringWithFormat:@"刚刚"];
        return str;
    }else if ((temp = timeInterval/60)<60){
        NSString * str  = [NSString stringWithFormat:@"%ld分钟前",temp];
        return str;

    }else if ((temp = timeInterval/(60*60))<24){
        NSString * str= [NSString stringWithFormat:@"%ld小时前",temp];
        return str;
    }else if((temp = timeInterval/(24*60*60))<30){
        NSString * str = [NSString stringWithFormat:@"%ld天前",temp];
        return str;
    }else if (((temp = timeInterval/(24*60*60*30)))<12){
        NSString * str = [NSString stringWithFormat:@"%ld月前",temp];
        return str;
    }else {
        temp = timeInterval/(24*60*60*30*12);
        NSString * str = [NSString stringWithFormat:@"%ld年前",temp];
        return str;
    }
}

+(NSString *)getLastString:(NSString *)str{
    if ([UtilTools isBlankString:str]) {
        return @"0";
    }else{
        if (str.length >4) {
            NSString * lastStr=[NSString stringWithFormat:@"%ldW",[str integerValue]/10000+[str integerValue]%10000];
            return lastStr;
            
        }else{
            return str;
        }
    }
}
/**
 *  获取当前时区的时间
 *
 *  @return 当前时区的时间
 */
+ (NSString *)getCurrentDate2:(NSString *)format
{
    //格林尼治日期
    NSDate *date = [NSDate date];
    //初始化时间格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //给时间格式设置时区（中国 东八区）
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [dateFormatter setTimeZone:timeZone];
    //给时间格式设置格式参数
    //YYYY:MM:dd-HH:mm:ss
    [dateFormatter setDateFormat:format];
    //获取date对应dateFormatter格式的字符串
    NSString *timeString = [dateFormatter stringFromDate:date];
    return timeString;
}

+(NSString*)stringFromDate:(NSDate*)date
{
    //用于格式化NSDate对象
    NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString*currentDateString=[dateFormatter stringFromDate:date];
    //输出currentDateString
    return currentDateString;
}
//获取当前时间
+(NSInteger )getTime{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒，不乘就是精确到秒
    
    return a;
}

+(NSString *)stringFromData:(NSData *)data
{
    NSString *result  =[[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return result;
}
//计算文本高度
+ (CGSize)getTextHeight:(NSString *)text width:(CGFloat)width font:(UIFont *)font
{
    
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return textRect.size;
}
//计算文本宽度
+ (CGSize)getTextHeight:(NSString *)text hight:(CGFloat)hight font:(UIFont *)font
{
    CGRect textRect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, hight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return textRect.size;
}
//计算textView的高度
+ (CGFloat)getTextViewHeight:(NSString *)text font:(UIFont*)font width:(CGFloat)width;
{
    //初始化textView
    UITextView *textView = [[UITextView alloc] init];
    [textView setText:text];
    [textView setFont:font];
    
    CGSize size = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return size.height;
}
+(NSString *)intervalSinceNow: (NSString *) theDate
{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    date.timeZone=[NSTimeZone timeZoneWithName:@"GMT"];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=now-late;
    if (cha/60<=1) {
        timeString=@"刚刚";
    }
    else  if (1<cha/60&&cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
        
    }
    else if (cha/3600>=1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    else if (cha/86400<30&&cha/86400>=1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
        
    }
    else if (cha/86400/30>=1&&cha/86400/30<12) {
        timeString = [NSString stringWithFormat:@"%f", cha/86400/30];
        timeString = [timeString substringToIndex:timeString.length-7];
        
        timeString=[NSString stringWithFormat:@"%@月前", timeString];
        
    }else{
        timeString = [NSString stringWithFormat:@"%f", cha/86400/30/12];
        timeString = [timeString substringToIndex:timeString.length-7];
        
        timeString=[NSString stringWithFormat:@"%@年前", timeString];
    }
    return timeString;
}


//录音格式转换（.caf > .mp3）
//+ (NSString *)toMp3:(NSString *)inputStringPath{
//    NSString *cafFilePath = inputStringPath;
//    if ([cafFilePath containsString:@"caf"]) {
//        NSDateFormatter *fileNameFormat=[[NSDateFormatter alloc] init];
//        [fileNameFormat setDateFormat:@"yyyyMMddhhmmss"];
//        NSString *mp3FileName = [fileNameFormat stringFromDate:[NSDate date]];
//        mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
//
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0];
//        NSString *strMp3Path = [[NSString alloc] initWithFormat:@"%@",documentsDirectory];
//        NSString *mp3FilePath = [strMp3Path stringByAppendingPathComponent:mp3FileName];
//
//        @try {
//            int read, write;
//
//            FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");//被转换的文件
//
//            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");//转换后文件的存放位置
//
//            const int PCM_SIZE = 8192;
//            const int MP3_SIZE = 8192;
//            short int pcm_buffer[PCM_SIZE*2];
//            unsigned char mp3_buffer[MP3_SIZE];
//
//            lame_t lame = lame_init();
//            lame_set_in_samplerate(lame, 44100);
//            lame_set_VBR(lame, vbr_default);
//            lame_init_params(lame);
//            if (!pcm) {
//                do {
//                    read = (int)fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
//                    if (read == 0)
//                        write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
//                    else
//                        write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
//
//                    fwrite(mp3_buffer, write, 1, mp3);
//
//                } while (read != 0);
//
//                lame_close(lame);
//                fclose(mp3);
//                fclose(pcm);
//
//            }
//        }
//        @catch (NSException *exception) {
//
//        }
//        @finally {
//
//            return mp3FilePath;
//
//        }
//
//    }
//    else
//    {
//        [MessageAlertView showErrorMessage:@"录音失败，请重录"];
//
//    }
//}
#pragma  mark  封装方法
+(UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
+ (UIImage *)getImage:(UIView *)shareView

{
    UIGraphicsBeginImageContextWithOptions(shareView.size, NO, 0.0);
    //currentView 当前的view  创建一个基于位图的图形上下文并指定大小为
    [shareView.layer renderInContext:UIGraphicsGetCurrentContext()];//renderInContext呈现接受者及其子范围到指定的上下文
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//返回一个基于当前图形上下文的图片
    UIGraphicsEndImageContext();//移除栈顶的基于当前位图的图形上下文
    
    return  viewImage;
    
}

+(NSString *)timeFormatted:(int)totalSeconds
{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
/**
 *  增加渐变色
 *
 *  @param colorArray 传入要渐变的色值数组
 *
 *  @return 返回的CAGradientLayer
 */
+(CAGradientLayer *)gradientPointStart:(CGPoint )startPoint endPoint:(CGPoint )endPoint frame:(CGRect )frame  colorArray:(NSArray *)colorArray{
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    gradientLayer.colors = colorArray;
    gradientLayer.locations = @[@0.0,@1.0];
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    gradientLayer.frame = frame;
    return  gradientLayer;
    
}
+(CALayer  *)layerColor:(UIColor * )color  Opacity:(float )opacity shadowOffset:(CGSize )shadowOffset  shadowRadius:(CGFloat )shadowRadius{
    CALayer *layer = [CALayer layer];
    
    layer.shadowColor=color.CGColor;
    layer.shadowOpacity=opacity;
    layer.shadowOffset = shadowOffset;
    layer.shadowRadius = shadowRadius;
    return  layer;
    
}

+ (BOOL)openEventServiceWithBolck
{
    __block BOOL Restrictedstate=YES;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    
    cellularData.cellularDataRestrictionDidUpdateNotifier =  ^(CTCellularDataRestrictedState state){
        //获取联网状态
        switch (state) {
            case kCTCellularDataRestricted:
                Restrictedstate=YES;
                break;
            case kCTCellularDataNotRestricted:
            case kCTCellularDataRestrictedStateUnknown:
                Restrictedstate=NO;
                break;
            default:
                break;
        };
    };
    
    CTCellularDataRestrictedState state = cellularData.restrictedState;
    switch (state) {
        case kCTCellularDataRestricted:
            Restrictedstate=YES;
            break;
        case kCTCellularDataNotRestricted:
            Restrictedstate=NO;
            break;
        case kCTCellularDataRestrictedStateUnknown:
            Restrictedstate=NO;
            break;
        default:
            break;
    };
#endif
    return Restrictedstate;
}
+(BOOL)haveQQ
{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]];
}
+(BOOL)haveWeiXin
{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]];
}
+ (int)getRandomNumber:(int)from to:(int)to

{
    
    return (int)(from + (arc4random() % (to-from + 1)));
    
}

+(void)refresh:(UITableView *)tableview Integer:(NSInteger)interger
{
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:interger];
    [tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
    
    
    
}

//打电话
+ (UIWebView *)call:(NSString *)phoneAccount
{
    NSString *callPhone = phoneAccount;
    UIWebView *callWebView = [[UIWebView alloc] init];
    NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",callPhone]];
    [callWebView loadRequest:[NSURLRequest requestWithURL:telURL]];
    return  callWebView;
}


//获取视频封面，本地视频，网络视频都可以用

+(UIImage*)thumbnailImageForVideo:(NSURL *)videoURL
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(1 * NSEC_PER_SEC, 3);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    if(error){
        DLog(@"截取视频缩略图时发生错误，错误信息：%@",error.localizedDescription);
    }
    CMTimeShow(actualTime);
    UIImage *thumbImg = [[UIImage alloc] initWithCGImage:image];
    return thumbImg;
    
}
+(void)PlaySoundFilename:(NSString *)filename FileType:(NSString *)filetype
{
    BOOL VoiceOn=  [[NSUserDefaults standardUserDefaults] boolForKey:@"kVoiceOn"];
    if (VoiceOn) {
        //播放自己的本地来电提示文件
        NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:filetype];
        if (path) {
            
            //扬声器 (WLS)
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            
            //注册声音到系统
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_enter_id);
            AudioServicesPlaySystemSound(shake_sound_enter_id);
            
            
        }
        
    }
}

+(void)StopPlaySound
{
    BOOL kShockOn=  [[NSUserDefaults standardUserDefaults] boolForKey:@"kShockOn"];
    if (kShockOn) {
        
        AudioServicesDisposeSystemSoundID(shake_sound_enter_id);
        
    }
}
//震动方法
+(void)vibrate{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

#pragma mark-> 获取扫描区域的比例关系
+(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    
    CGFloat x,y,width,height;
    
    x = (CGRectGetHeight(readerViewBounds)-CGRectGetHeight(rect))/2/CGRectGetHeight(readerViewBounds);
    y = (CGRectGetWidth(readerViewBounds)-CGRectGetWidth(rect))/2/CGRectGetWidth(readerViewBounds);
    width = CGRectGetHeight(rect)/CGRectGetHeight(readerViewBounds);
    height = CGRectGetWidth(rect)/CGRectGetWidth(readerViewBounds);
    
    return CGRectMake(x, y, width, height);
    
}
///十六进制转换2进制
+(NSString *)getBinaryByHex:(NSString *)hex{
    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"A"];
    [hexDic setObject:@"1011" forKey:@"B"];
    [hexDic setObject:@"1100" forKey:@"C"];
    [hexDic setObject:@"1101" forKey:@"D"];
    [hexDic setObject:@"1110" forKey:@"E"];
    [hexDic setObject:@"1111" forKey:@"F"];
    
    
    NSMutableString *binary = [NSMutableString string];
    for (int i = 0; i < hex.length; i++) {
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        
        key = key.uppercaseString; //不管三七二十一,先转为大写字母再说
        NSString *binaryStr = hexDic[key];
        
        [binary appendString:[NSString stringWithFormat:@"%@",binaryStr]];
    }
    
    
    return binary;
}
///二进制转化16进制
+ (NSString *)getHexByBinary:(NSString *)binary{
    NSMutableDictionary *binaryDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [binaryDic setObject:@"0" forKey:@"0000"];
    [binaryDic setObject:@"1" forKey:@"0001"];
    [binaryDic setObject:@"2" forKey:@"0010"];
    [binaryDic setObject:@"3" forKey:@"0011"];
    [binaryDic setObject:@"4" forKey:@"0100"];
    [binaryDic setObject:@"5" forKey:@"0101"];
    [binaryDic setObject:@"6" forKey:@"0110"];
    [binaryDic setObject:@"7" forKey:@"0111"];
    [binaryDic setObject:@"8" forKey:@"1000"];
    [binaryDic setObject:@"9" forKey:@"1001"];
    [binaryDic setObject:@"A" forKey:@"1010"];
    [binaryDic setObject:@"B" forKey:@"1011"];
    [binaryDic setObject:@"C" forKey:@"1100"];
    [binaryDic setObject:@"D" forKey:@"1101"];
    [binaryDic setObject:@"E" forKey:@"1110"];
    [binaryDic setObject:@"F" forKey:@"1111"];
    
    if (binary.length % 4 != 0) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 4 - binary.length % 4; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    NSString *hex = @"";
    for (int i=0; i<binary.length; i+=4) {
        
        NSString *key = [binary substringWithRange:NSMakeRange(i, 4)];
        NSString *value = [binaryDic objectForKey:key];
        if (value) {
            
            hex = [hex stringByAppendingString:value];
        }
    }
    return hex;
}

#pragma mark 加密算法


+(NSString *)base64EncodedString:(NSString *)baseString
{
    NSData *data = [baseString dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}
+ (NSString *) encode:(NSString *)str key:(NSString *)key
{
    // doCipher 不能编汉字，所以要进行 url encode
    NSMutableString* str1 = [self urlEncode:str];
    NSMutableString* encode = [NSMutableString stringWithString:[self doCipher:str1 key:key context:kCCEncrypt]];
    return encode;
}
+ (NSMutableString *)urlEncode:(NSString*)str
{
    
    NSMutableString* encodeStr = [NSMutableString stringWithString: [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];;
    
    [encodeStr replaceOccurrencesOfString:@"+" withString:@"%2B" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
    [encodeStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSWidthInsensitiveSearch range:NSMakeRange(0, [encodeStr length])];
    return encodeStr;
}

+ (NSString *) decode:(NSString *)str key:(NSString *)key
{
    NSMutableString *str1 = [NSMutableString stringWithString:str];
    NSString *rt = [self doCipher:str1 key:key context:kCCDecrypt];
    return rt;
}
+ (NSString *)doCipher:(NSString *)sTextIn key:(NSString *)sKey
               context:(CCOperation)encryptOrDecrypt {
    NSStringEncoding EnC = NSUTF8StringEncoding;
    
    NSMutableData *dTextIn;
    if (encryptOrDecrypt == kCCDecrypt) {
        dTextIn = [[UtilTools decodeBase64WithString:sTextIn] mutableCopy];
    }
    else{
        dTextIn = [[sTextIn dataUsingEncoding: EnC] mutableCopy];
    }
    NSMutableData * dKey = [[sKey dataUsingEncoding:EnC] mutableCopy];
    [dKey setLength:kCCBlockSizeDES];
    uint8_t *bufferPtr1 = NULL;
    size_t bufferPtrSize1 = 0;
    size_t movedBytes1 = 0;
    bufferPtrSize1 = ([sTextIn length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    bufferPtr1 = malloc(bufferPtrSize1 * sizeof(uint8_t));
    memset((void *)bufferPtr1, 0x00, bufferPtrSize1);
    
    CCCrypt(encryptOrDecrypt, // CCOperation op
            kCCAlgorithmDES, // CCAlgorithm alg
            kCCOptionPKCS7Padding, // CCOptions options
            [dKey bytes], // const void *key
            [dKey length], // size_t keyLength //
            [dKey bytes], // const void *iv
            [dTextIn bytes], // const void *dataIn
            [dTextIn length],  // size_t dataInLength
            (void *)bufferPtr1, // void *dataOut
            bufferPtrSize1,     // size_t dataOutAvailable
            &movedBytes1);
    
    
    NSString * sResult;
    if (encryptOrDecrypt == kCCDecrypt){
        sResult = [[NSString alloc] initWithData:[NSData dataWithBytes:bufferPtr1 length:movedBytes1] encoding:EnC];
        free(bufferPtr1);
    }
    else {
        NSData *dResult = [NSData dataWithBytes:bufferPtr1 length:movedBytes1];
        free(bufferPtr1);
        sResult = [self encodeBase64WithData:dResult];
    }
    return sResult;
}
+ (NSString *)encodeBase64WithData:(NSData *)objData
{
    NSString *encoding = nil;
    unsigned char *encodingBytes = NULL;
    @try {
        static char encodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        static NSUInteger paddingTable[] = {0,2,1};
        
        NSUInteger dataLength = [objData length];
        NSUInteger encodedBlocks = (dataLength * 8) / 24;
        NSUInteger padding = paddingTable[dataLength % 3];
        if( padding > 0 ) encodedBlocks++;
        NSUInteger encodedLength = encodedBlocks * 4;
        
        encodingBytes = malloc(encodedLength);
        if( encodingBytes != NULL ) {
            NSUInteger rawBytesToProcess = dataLength;
            NSUInteger rawBaseIndex = 0;
            NSUInteger encodingBaseIndex = 0;
            unsigned char *rawBytes = (unsigned char *)[objData bytes];
            unsigned char rawByte1, rawByte2, rawByte3;
            while( rawBytesToProcess >= 3 ) {
                rawByte1 = rawBytes[rawBaseIndex];
                rawByte2 = rawBytes[rawBaseIndex+1];
                rawByte3 = rawBytes[rawBaseIndex+2];
                encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
                encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
                encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) | ((rawByte3 >> 6) & 0x03) ];
                encodingBytes[encodingBaseIndex+3] = encodingTable[(rawByte3 & 0x3F)];
                
                rawBaseIndex += 3;
                encodingBaseIndex += 4;
                rawBytesToProcess -= 3;
            }
            rawByte2 = 0;
            switch (dataLength-rawBaseIndex) {
                case 2:
                    rawByte2 = rawBytes[rawBaseIndex+1];
                case 1:
                    rawByte1 = rawBytes[rawBaseIndex];
                    encodingBytes[encodingBaseIndex] = encodingTable[((rawByte1 >> 2) & 0x3F)];
                    encodingBytes[encodingBaseIndex+1] = encodingTable[((rawByte1 << 4) & 0x30) | ((rawByte2 >> 4) & 0x0F) ];
                    encodingBytes[encodingBaseIndex+2] = encodingTable[((rawByte2 << 2) & 0x3C) ];
                    // we can skip rawByte3 since we have a partial block it would always be 0
                    break;
            }
            // compute location from where to begin inserting padding, it may overwrite some bytes from the partial block encoding
            // if their value was 0 (cases 1-2).
            encodingBaseIndex = encodedLength - padding;
            while( padding-- > 0 ) {
                encodingBytes[encodingBaseIndex++] = '=';
            }
            encoding = [[NSString alloc] initWithBytes:encodingBytes length:encodedLength encoding:NSASCIIStringEncoding];
        }
    }
    @catch (NSException *exception) {
        encoding = nil;
    }
    @finally {
        if( encodingBytes != NULL ) {
            free( encodingBytes );
        }
    }
    return encoding;
    
}

+ (NSData *)decodeBase64WithString:(NSString *)strBase64
{
    NSData *data = nil;
    unsigned char *decodedBytes = NULL;
    @try {
#define __ 255
        static char decodingTable[256] = {
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x00 - 0x0F
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x10 - 0x1F
            __,__,__,__, __,__,__,__, __,__,__,62, __,__,__,63,  // 0x20 - 0x2F
            52,53,54,55, 56,57,58,59, 60,61,__,__, __, 0,__,__,  // 0x30 - 0x3F
            __, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,  // 0x40 - 0x4F
            15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__,  // 0x50 - 0x5F
            __,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,  // 0x60 - 0x6F
            41,42,43,44, 45,46,47,48, 49,50,51,__, __,__,__,__,  // 0x70 - 0x7F
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x80 - 0x8F
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0x90 - 0x9F
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xA0 - 0xAF
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xB0 - 0xBF
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xC0 - 0xCF
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xD0 - 0xDF
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xE0 - 0xEF
            __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,  // 0xF0 - 0xFF
        };
        strBase64 = [strBase64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
        NSData *encodedData = [strBase64 dataUsingEncoding:NSASCIIStringEncoding];
        unsigned char *encodedBytes = (unsigned char *)[encodedData bytes];
        
        NSUInteger encodedLength = [encodedData length];
        NSUInteger encodedBlocks = (encodedLength+3) >> 2;
        NSUInteger expectedDataLength = encodedBlocks * 3;
        
        unsigned char decodingBlock[4];
        
        decodedBytes = malloc(expectedDataLength);
        if( decodedBytes != NULL ) {
            
            NSUInteger i = 0;
            NSUInteger j = 0;
            NSUInteger k = 0;
            unsigned char c;
            while( i < encodedLength ) {
                c = decodingTable[encodedBytes[i]];
                i++;
                if( c != __ ) {
                    decodingBlock[j] = c;
                    j++;
                    if( j == 4 ) {
                        decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
                        decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
                        decodedBytes[k+2] = (decodingBlock[2] << 6) | (decodingBlock[3]);
                        j = 0;
                        k += 3;
                    }
                }
            }
            
            // Process left over bytes, if any
            if( j == 3 ) {
                decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
                decodedBytes[k+1] = (decodingBlock[1] << 4) | (decodingBlock[2] >> 2);
                k += 2;
            } else if( j == 2 ) {
                decodedBytes[k] = (decodingBlock[0] << 2) | (decodingBlock[1] >> 4);
                k += 1;
            }
            data = [[NSData alloc] initWithBytes:decodedBytes length:k];
        }
    }
    @catch (NSException *exception) {
        data = nil;
    }
    @finally {
        if( decodedBytes != NULL ) {
            free( decodedBytes );
        }
    }
    return data;
    
}

+ (UIViewController *)getCurrentVC
{
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (1) {
        
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
        
    }
    
    return vc;
    
   
}

+ (NSInteger)characterCountOfStr:(NSString *)str;
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* data = [str dataUsingEncoding:enc];
    return [data length];
}
+(NSString *) sha1:(NSString *)input
{
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

+(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    NSString * str=mutStr.copy;
    return str;
    
}
//json转字典
+(NSDictionary *) JSONStringToDictionaryWithData:(NSString *)data{
    NSError * error;
    NSData * m_data = [data  dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization  JSONObjectWithData:m_data options:NSJSONReadingMutableContainers error:&error];
    return dict;
}
+(NSString *)isTimeOrDatas:(NSTimeInterval )smsDate{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:smsDate];
    NSString *dateSMS = [dateFormatter stringFromDate:date];
    NSDate *now = [NSDate date];
    NSString *dateNow = [dateFormatter stringFromDate:now];
    if ([dateSMS isEqualToString:dateNow]) {
        [dateFormatter setDateFormat:@"HH:mm"];
    }
    else {
        [dateFormatter setDateFormat:@"MM/dd"];
    }
    dateSMS = [dateFormatter stringFromDate:date];
    
    return dateSMS;
}
+(NSString *)getDifferenceUUID{
    NSString*result;
    
//    if([[[UIDevice currentDevice] systemVersion] floatValue] >6.0)
//
//    {
//
        result = [[NSUUID UUID] UUIDString];
    result = [result stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
//    }
//
//    else
//
//    {
//
//        CFUUIDRef uuidRef = CFUUIDCreate(NULL);
//
//        CFStringRef uuid = CFUUIDCreateString(NULL, uuidRef);
//
//        CFRelease(uuidRef);
//
//        result = ((_ *))uuid;
//
//    }
    return result;
}
+ (NSString *)ReturnString:(NSString *)str{
    if ([self isBlankString:str]) {
        return @"";
    }
    return str;
}

+(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize string:(NSString *)string{

NSDictionary *attrs = @{NSFontAttributeName:font};

return [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;

}

+(CGFloat)heightWithFont:(UIFont *)font maxWidth:(CGFloat)maxWidth string:(NSString *)string{
    return [UtilTools sizeWithFont:font maxSize:CGSizeMake(maxWidth, MAXFLOAT) string:string].height;
}
@end
